package com.ansion.baseui.base.recycler;

import android.util.Pair;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.facebook.drawee.backends.pipeline.Fresco;

import java.util.ArrayList;


/***
 * @author john 2023-3-1
 * @desc 用于实现滑动快速滑动暂停fresco下载任务，停止滑动恢复被暂停的下载任务
 *
 * 大致原理滑动期间，只往任务队列添加，不执行；停止滑动遍历所有的任务队列挨个submit到线程池
 */
public class FrescoStateOnScrollSpeedListener extends RecyclerView.OnScrollListener {
    private final ArrayList<Pair<Integer, Long>> trackScrollList = new ArrayList<>(2);

    private SearchBarSpringAnimation animation;

    public void setSpringAnimation(SearchBarSpringAnimation animation) {
        this.animation = animation;
    }

    @Override
    public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            if (Fresco.getImagePipeline().isPaused()) {
                Fresco.getImagePipeline().resume();
            }
            if (animation != null) {
                animation.play(recyclerView);
            }
        }
    }


    @Override
    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
        try {
            if (trackScrollList.size() < 2) {
                Pair<Integer, Long> pair = new Pair<>(dy, System.currentTimeMillis());
                trackScrollList.add(pair);
                if (trackScrollList.size() == 2) {
                    //计算速度
                    Pair<Integer, Long> pair1 = trackScrollList.get(0);
                    Pair<Integer, Long> pair2 = trackScrollList.get(1);
                    long diffTime = Math.abs(pair1.second - pair2.second);
                    int diffDy = Math.abs(pair1.first - pair2.first);
                    long speed = (diffDy * 1000) / diffTime;
                    //清空trackScrollList
                    trackScrollList.clear();

                    if (speed > 3000) {
                        if (!Fresco.getImagePipeline().isPaused()) {
                            Fresco.getImagePipeline().pause();
                        }
                    } else if (speed < 200) {
                        if (Fresco.getImagePipeline().isPaused()) {
                            Fresco.getImagePipeline().resume();
                        }

                    }

                }
            }
        } catch (Exception e) {

        }

    }
}
